package geowiki.threads;

import java.util.ArrayList;
import java.util.List;

import processing.core.PApplet;
import processing.core.PImage;
import processing.xml.XMLElement;

public class ImageThreadTestApp extends PApplet {

	List<AppearingImage> images = new ArrayList<AppearingImage>();
	AppearingImage selectedImage = null;

	String feedUrl = "http://ffffound.com/home/tillnm/found/feed";

	public void setup() {
		size(600, 600);
		smooth();
		loadFeed();
	}

	public void draw() {
		background(230);

		for (int i = 0; i < images.size(); i++) {
			AppearingImage img = images.get(i);
			img.update();
			img.draw();
		}

		if (selectedImage != null) {
			selectedImage.draw();
		}
	}

	public void mousePressed() {
		if (selectedImage != null) {
			// Deselect current one
			selectedImage.zoomOut();
			selectedImage = null;
		} else {
			// Only allow zooming in, if currently none is selected
			int i = 0;
			while (i < images.size() && selectedImage == null) {
				AppearingImage img = images.get(i);
				if (img.isOver(mouseX, mouseY)) {
					selectedImage = img;
					selectedImage.zoomIn();
				}
				i++;
			}
		}
	}

	public void onImageLoaded(PImage img, int index) {
		float x = (5 - (5 - (index % 5))) * 110 + 80;
		float y = (float) Math.floor(index / 5) * 110 + 80;

		AppearingImage aImg = new AppearingImage(this, img, x, y);
		images.add(aImg);
	}

	public void loadFeed() {
		XMLElement rss = new XMLElement(this, feedUrl);
		// Get thumbnail of each element
		XMLElement[] imageURLElements = rss.getChildren("channel/item/media:content");
		for (int i = 0; i < imageURLElements.length; i++) {
			String imageURL = imageURLElements[i].getStringAttribute("url");
			Thread thread = new ImageLoadThread(this, imageURL, i);
			thread.start();
		}
	}

}
